package org.zhaya.sdk.util;

import jdk.nashorn.api.scripting.ClassFilter;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.zhaya.sdk.processors.custom.PluginProcess;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * js转Java ScriptEngine
 *
 * @author jackl
 */
public class JavaScriptFactory {
    /**
     * add the full qualified name to  be filtered.
     */
    static class MyCF implements ClassFilter {
        @Override
        public boolean exposeToScripts(String s) {
            return s.compareTo(System.class.getName()) != 0;
        }
    }

    public static PluginProcess getPluginProcessor(String sourceCode) throws ScriptException {
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        ScriptEngine engine = factory.getScriptEngine(new MyCF());
        engine.eval(sourceCode);
        Invocable inv = (Invocable) engine;
        PluginProcess pluginProcess = inv.getInterface(PluginProcess.class);
        return pluginProcess;
    }
}